<template>
  <div>
    <el-card style="width: 100%; height: 100%">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">物料管理</el-breadcrumb-item>
        <el-breadcrumb-item>物料管理</el-breadcrumb-item>
        <el-breadcrumb-item>物料信息管理</el-breadcrumb-item>
        <el-breadcrumb-item>物料信息管理列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card style="width: 100%; height: 100%; margin-top: 5px">
      <el-form :inline="true" :model="queryForm" label-width="auto">
        <el-form-item label="物料编号">
          <el-input
            v-model="queryForm.materialCode"
            placeholder="请输入物料编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="queryForm.materialName"
            placeholder="请输入物料名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="物料类型" style="width: 250px;">
          <el-select
          style="width: 200px;"
            v-model="queryForm.materialType"
            placeholder="请选择物料类型"
            clearable
          >
            <el-option
            style="width: 200px;"
              v-for="item in materialTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-dropdown>
            <el-button type="info">
              更多
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleExport">导出全部</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
      <div style="margin-top: 10px">
        <el-button type="success" plain @click="handleAdd">新增+</el-button>
        <el-button type="warning" plain @click="handleImport">导入</el-button>
        <el-button type="primary" plain @click="handleExport">导出</el-button>
        <el-button type="danger" plain :disabled="!multipleSelection.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
      <el-table
        style="width: 100%; margin-top: 10px"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
        :loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="70" />
        <el-table-column prop="materialCode" label="物料编号" />
        <el-table-column prop="materialName" label="物料名称" />
        <el-table-column prop="specification" label="规格型号" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="materialTypeLabel" label="物料类型" />
        <el-table-column prop="materialAttributeLabel" label="物料属性" />
        <el-table-column prop="materialCategoryLabel" label="物料分类" />
        <el-table-column prop="statusLabel" label="状态" width="90" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <table style="margin-top: 10px; width: 100%">
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[1, 2, 3, 5]"
              background
              layout="slot,total,sizes"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </td>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="slot,prev, pager"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              prev-text="上一页"
            >
              <template #default>
                <el-button type="primary" link @click="handleCurrentChange(1)">
                  首页
                </el-button>
              </template>
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="next,slot,jumper"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              next-text="下一页"
            >
              <template #default>
                <el-button
                  type="primary"
                  link
                  @click="handleCurrentChange(pagination.pageCount || 1)"
                >
                  尾页
                </el-button>
              </template>
            </el-pagination>
          </td>
        </tr>
      </table>
    </el-card>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="auto"
        style="max-width: 560px"
      >
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="物料编号" prop="materialCode">
              <el-input v-model="formModel.materialCode" placeholder="请输入物料编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="formModel.materialName" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="formModel.specification" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formModel.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="物料类型" prop="materialType">
              <el-select v-model="formModel.materialType" placeholder="请选择物料类型">
                <el-option
                  v-for="item in materialTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料属性" prop="materialAttribute">
              <el-select v-model="formModel.materialAttribute" placeholder="请选择物料属性">
                <el-option
                  v-for="item in materialAttributeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="物料分类" prop="materialCategory">
              <el-select v-model="formModel.materialCategory" placeholder="请选择物料分类">
                <el-option
                  v-for="item in materialCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formModel.status" placeholder="请选择状态">
                <el-option
                  v-for="item in statusOptions"
                  :key="String(item.value)"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="有效期限(天)" prop="materialDays">
              <el-input-number v-model="formModel.materialDays" :min="0" placeholder="请输入有效期限" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警天数" prop="materialStopDays">
              <el-input-number v-model="formModel.materialStopDays" :min="0" placeholder="请输入报警天数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="库存上限" prop="materialUpper">
              <el-input-number v-model="formModel.materialUpper" :min="0" placeholder="请输入库存上限" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存下限" prop="materialDown">
              <el-input-number v-model="formModel.materialDown" :min="0" placeholder="请输入库存下限" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="12">
          <el-col :span="12">
            <el-form-item label="采购价格" prop="materialMoney">
              <el-input-number v-model="formModel.materialMoney" :min="0" :precision="2" placeholder="请输入采购价格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formModel.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSubmit">保存</el-button>
          <el-button type="primary" @click="dialogVisible = false">取消</el-button>
          <el-button type="warning" @click="handleResetForm">重置</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight, ArrowDown } from "@element-plus/icons-vue";
import https from "@/Http/http";
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

// 写库 API 基础地址（也可以直接使用 https.Writes 实例）
const WRITE_API_BASE = "http://localhost:5214";

// 后端DTO接口
interface MaterialDTO {
  id: number;
  materialcard: string;
  materialname: string;
  materialmodelsame: string;
  materialunit: string;
  materialtypeid: number;
  materialattributeid: number;
  materialclassificationid: number;
  materialstate: boolean;
  materialdays: number;
  materialstopdays: number;
  materialupper: number;
  materialdown: number;
  materialmoney: number;
  materialdes: string;
  materialphoto: string;
  materialfile: string;
}

// 前端显示用的接口
interface MaterialRow {
  id: number;
  materialCode: string;
  materialName: string;
  specification: string;
  unit: string;
  materialType: number | null;
  materialAttribute: number | null;
  materialCategory: number | null;
  status: boolean;
  remark?: string;
  materialDays?: number;
  materialStopDays?: number;
  materialUpper?: number;
  materialDown?: number;
  materialMoney?: number;
  // 后端字段（用于编辑时）
  materialtypeid?: number;
  materialattributeid?: number;
  materialclassificationid?: number;
  materialstate?: boolean;
  materialdes?: string;
  materialdays?: number;
  materialstopdays?: number;
  materialupper?: number;
  materialdown?: number;
  materialmoney?: number;
  materialphoto?: string;
  materialfile?: string;
}

interface MaterialTableRow extends MaterialRow {
  index: number;
  materialTypeLabel: string;
  materialAttributeLabel: string;
  materialCategoryLabel: string;
  statusLabel: string;
}

// API响应接口
interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

interface ApiResultResponse<T> {
  code: number;
  msg: string;
  data: T;
}

const loading = ref(false);
const tableData = ref<MaterialTableRow[]>([]);
const multipleSelection = ref<MaterialRow[]>([]);

const queryForm = reactive({
  materialCode: "",
  materialName: "",
  materialType: null as number | null,
});

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

// 物料类型选项（这里需要根据实际业务从API获取，暂时使用示例数据）
const materialTypeOptions = [
  { label: "类型一", value: 1 },
  { label: "类型二", value: 2 },
  { label: "类型三", value: 3 },
];

// 物料属性选项
const materialAttributeOptions = [
  { label: "自制", value: 1 },
  { label: "外购", value: 2 },
];

// 物料分类选项
const materialCategoryOptions = [
  { label: "分类一", value: 1 },
  { label: "分类二", value: 2 },
  { label: "分类三", value: 3 },
];

// 状态选项
const statusOptions = [
  { label: "启用", value: true },
  { label: "停用", value: false },
];

const materialTypeMap = computed(() =>
  materialTypeOptions.reduce<Record<number, string>>((acc, cur) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {})
);

const materialAttributeMap = computed(() =>
  materialAttributeOptions.reduce<Record<number, string>>((acc, cur) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {})
);

const materialCategoryMap = computed(() =>
  materialCategoryOptions.reduce<Record<number, string>>((acc, cur) => {
    acc[cur.value] = cur.label;
    return acc;
  }, {})
);

const statusMap = computed(() =>
  statusOptions.reduce<Record<string, string>>((acc, cur) => {
    acc[String(cur.value)] = cur.label;
    return acc;
  }, {})
);

// 将后端DTO转换为前端显示格式
const dtoToRow = (dto: MaterialDTO, index: number): MaterialTableRow => {
  return {
    id: dto.id,
    materialCode: dto.materialcard || "",
    materialName: dto.materialname || "",
    specification: dto.materialmodelsame || "",
    unit: dto.materialunit || "",
    materialType: dto.materialtypeid,
    materialAttribute: dto.materialattributeid,
    materialCategory: dto.materialclassificationid,
    status: dto.materialstate,
    remark: dto.materialdes || "",
    materialDays: dto.materialdays,
    materialStopDays: dto.materialstopdays,
    materialUpper: dto.materialupper,
    materialDown: dto.materialdown,
    materialMoney: dto.materialmoney,
    index,
    materialTypeLabel: materialTypeMap.value[dto.materialtypeid] || `类型${dto.materialtypeid}`,
    materialAttributeLabel: materialAttributeMap.value[dto.materialattributeid] || `属性${dto.materialattributeid}`,
    materialCategoryLabel: materialCategoryMap.value[dto.materialclassificationid] || `分类${dto.materialclassificationid}`,
    statusLabel: statusMap.value[String(dto.materialstate)] || "--",
    // 保留后端字段用于编辑
    materialtypeid: dto.materialtypeid,
    materialattributeid: dto.materialattributeid,
    materialclassificationid: dto.materialclassificationid,
    materialstate: dto.materialstate,
    materialdes: dto.materialdes,
    materialdays: dto.materialdays,
    materialstopdays: dto.materialstopdays,
    materialupper: dto.materialupper,
    materialdown: dto.materialdown,
    materialmoney: dto.materialmoney,
    materialphoto: dto.materialphoto,
    materialfile: dto.materialfile,
  };
};

// 将前端表单数据转换为后端请求格式
const rowToRequest = (row: MaterialRow) => {
  return {
    id: row.id || 0,
    MaterialCard: row.materialCode,
    MaterialName: row.materialName,
    MaterialModelSame: row.specification,
    MaterialUnit: row.unit,
    MaterialTypeId: row.materialType || row.materialtypeid || 0,
    MaterialAttributeId: row.materialAttribute || row.materialattributeid || 0,
    MaterialClassificationId: row.materialCategory || row.materialclassificationid || 0,
    MaterialState: row.status !== undefined ? row.status : (row.materialstate !== undefined ? row.materialstate : true),
    MaterialDays: row.materialDays || row.materialdays || 0,
    MaterialStopDays: row.materialStopDays || row.materialstopdays || 0,
    MaterialUpper: row.materialUpper || row.materialupper || 0,
    MaterialDown: row.materialDown || row.materialdown || 0,
    MaterialMoney: row.materialMoney || row.materialmoney || 0,
    MaterialDes: row.remark || row.materialdes || "",
    MaterialPhoto: row.materialphoto || "",
    MaterialFile: row.materialfile || "",
  };
};

// 获取列表数据
const fetchTableData = () => {
  loading.value = true;
  const params: any = {
    pageindex: pagination.pageIndex,
    pagesize: pagination.pageSize,
  };

  // 添加查询条件
  // 物料编号或物料名称都映射到materialname参数（后端API支持通过名称/编号搜索）
  if (queryForm.materialCode || queryForm.materialName) {
    params.materialname = queryForm.materialCode || queryForm.materialName;
  }
  if (queryForm.materialType !== null) {
    params.materialtypeid = queryForm.materialType;
  }

  https.Reads
    .get<ApiPageingResponse<MaterialDTO>>(`/Material/MaterialGetList`, {
      params,
    })
    .then((res) => {
      const response = res.data;
      if (response.code === 1) {
        tableData.value = (response.data || []).map((item, index) =>
          dtoToRow(item, (pagination.pageIndex - 1) * pagination.pageSize + index + 1)
        );
        pagination.totalCount = response.totalCount || 0;
        pagination.pageCount = response.pageCount || 0;
      } else {
        ElMessage.error(response.msg || "获取数据失败");
        tableData.value = [];
        pagination.totalCount = 0;
        pagination.pageCount = 0;
      }
    })
    .catch((error) => {
      console.error("获取数据失败:", error);
      ElMessage.error("获取数据失败，请稍后再试");
      tableData.value = [];
      pagination.totalCount = 0;
      pagination.pageCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  fetchTableData();
});

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  fetchTableData();
};

const handleSelectionChange = (val: MaterialRow[]) => {
  multipleSelection.value = val;
};

const handleQuery = () => {
  pagination.pageIndex = 1;
  fetchTableData();
};

const handleReset = () => {
  queryForm.materialCode = "";
  queryForm.materialName = "";
  queryForm.materialType = null;
  handleQuery();
};

const handleImport = () => {
  ElMessage.info("导入功能待实现");
};

const handleExport = () => {
  ElMessage.info("导出功能待实现");
};

const formRef = ref<FormInstance>();
const dialogVisible = ref(false);
const dialogTitle = ref("");

const defaultFormModel: MaterialRow = {
  id: 0,
  materialCode: "",
  materialName: "",
  specification: "",
  unit: "",
  materialType: null,
  materialAttribute: null,
  materialCategory: null,
  status: true,
  remark: "",
  materialDays: 0,
  materialStopDays: 0,
  materialUpper: 0,
  materialDown: 0,
  materialMoney: 0,
};

const formModel = reactive<MaterialRow>({ ...defaultFormModel });

const rules = reactive<FormRules>({
  materialCode: [{ required: true, message: "物料编号不可为空", trigger: "blur" }],
  materialName: [{ required: true, message: "物料名称不可为空", trigger: "blur" }],
  specification: [{ required: true, message: "规格型号不可为空", trigger: "blur" }],
  unit: [{ required: true, message: "单位不可为空", trigger: "blur" }],
  materialType: [{ required: true, message: "请选择物料类型", trigger: "change" }],
  materialAttribute: [{ required: true, message: "请选择物料属性", trigger: "change" }],
  materialCategory: [{ required: true, message: "请选择物料分类", trigger: "change" }],
});

const handleAdd = () => {
  router.push('/MaterialAdd');
};

const handleEdit = (row: MaterialTableRow) => {
  dialogTitle.value = "物料信息编辑";
  // 将表格行数据转换为表单数据
  Object.assign(formModel, {
    id: row.id,
    materialCode: row.materialCode,
    materialName: row.materialName,
    specification: row.specification,
    unit: row.unit,
    materialType: row.materialType,
    materialAttribute: row.materialAttribute,
    materialCategory: row.materialCategory,
    status: row.status,
    remark: row.remark,
    materialDays: row.materialDays,
    materialStopDays: row.materialStopDays,
    materialUpper: row.materialUpper,
    materialDown: row.materialDown,
    materialMoney: row.materialMoney,
    // 保留后端字段
    materialtypeid: row.materialtypeid,
    materialattributeid: row.materialattributeid,
    materialclassificationid: row.materialclassificationid,
    materialstate: row.materialstate,
    materialdes: row.materialdes,
    materialdays: row.materialdays,
    materialstopdays: row.materialstopdays,
    materialupper: row.materialupper,
    materialdown: row.materialdown,
    materialmoney: row.materialmoney,
    materialphoto: row.materialphoto,
    materialfile: row.materialfile,
  });
  dialogVisible.value = true;
};

const handleResetForm = () => {
  Object.assign(formModel, defaultFormModel);
};

const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (!valid) {
      return;
    }

    const requestData = rowToRequest(formModel);
    const isEdit = formModel.id > 0;
    const url = isEdit
      ? `/MaterialAdd/MaterilUpdate`
      : `/MaterialAdd/MaterilAdd`;
    const method = isEdit ? "put" : "post";

    https.Writes[method]<ApiResultResponse<number>>(url, requestData)
      .then((res) => {
        const response = res.data;
        if (response.code === 1) {
          ElMessage.success(response.msg || "操作成功");
          dialogVisible.value = false;
          fetchTableData();
        } else {
          ElMessage.error(response.msg || "操作失败");
        }
      })
      .catch((error) => {
        console.error("操作失败:", error);
        ElMessage.error("请求失败，请稍后再试");
      });
  });
};

const handleDelete = (row: MaterialRow) => {
  ElMessageBox.confirm("确认删除当前物料信息吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes
        .delete<ApiResultResponse<number>>(`/MaterialAdd/MaterilDel`, {
          data: { id: row.id },
        })
        .then((res) => {
          const response = res.data;
          if (response.code === 1) {
            ElMessage.success(response.msg || "删除成功");
            fetchTableData();
          } else {
            ElMessage.error(response.msg || "删除失败");
          }
        })
        .catch((error) => {
          console.error("删除失败:", error);
          ElMessage.error("删除失败，请稍后再试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的物料");
    return;
  }
  ElMessageBox.confirm(`确认批量删除所选 ${multipleSelection.value.length} 个物料吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 由于没有批量删除接口，循环调用单个删除接口
      const deletePromises = multipleSelection.value.map((item) =>
        https.Writes.delete<ApiResultResponse<number>>(`/MaterialAdd/MaterilDel`, {
          data: { id: item.id },
        })
      );

      Promise.all(deletePromises)
        .then((results) => {
          const successCount = results.filter((res) => res.data.code === 1).length;
          if (successCount === multipleSelection.value.length) {
            ElMessage.success(`成功删除 ${successCount} 个物料`);
            fetchTableData();
          } else {
            ElMessage.warning(`部分删除成功，成功 ${successCount} 个，失败 ${multipleSelection.value.length - successCount} 个`);
            fetchTableData();
          }
        })
        .catch((error) => {
          console.error("批量删除失败:", error);
          ElMessage.error("批量删除失败，请稍后再试");
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>

